import config from '../../config'
import * as httpm from 'typed-rest-client/HttpClient'
import * as httpI from 'typed-rest-client/Interfaces'
import * as log from '../../log'

/**
 * 设置代理，用于fiddle抓包 调试用
 */
let httpc: httpm.HttpClient = new httpm.HttpClient('')
if (config.openApi.proxy) {
    let proxyConfig: httpI.IProxyConfiguration = {
        proxyUrl: 'http://127.0.0.1:8888'
    }
    let requestOption: httpI.IRequestOptions = {
        proxy: proxyConfig
    }
    httpc = new httpm.HttpClient('', undefined, requestOption);
}

/**
 * 通用响应类，无分页
 */
export class RSM<T>
{
    /// 响应代码
    public code: string;
    /// 响应描述
    public description: string;
    /// 响应数据
    public resData: T;
}
/// 通用响应类
export class RSMP<T>
{
    /// 响应代码
    public code: string;
    /// 响应描述
    public description: string
    /// 响应数据
    public resData: DataPageInfo<T>
}

export class DataPageInfo<T>
{
    /// 分页信息
    public pageInfo: pageInfo;
    /// 响应数据集合
    public list: T[]
}

export class pageInfo {
    /// 总条数
    public totalCount: number;
    /// 当前页条数
    public pageCount: number;
}

/**
 * http 请求
 * @param url 
 * @param rst 
 * @param userInfo 登录信息，用于设置 header 头
 */
export async function exec<T>(url: string, rst: object, userInfo?: any) {
    let headers = {
        "Content-Type": "application/json",
        "clientType": 14,
        "tempID": '',
        "userToken": '',
        "userUID": '',
        "Connection": 'Keep-Alive',
        "Keep-Alive": 300,
    }
    if (userInfo) {
        headers['tempID'] = userInfo['tempID']
        headers['userToken'] = userInfo['token']
        headers['userUID'] = userInfo['uid']
    }

    // console.log('url:',config.openApi.url + url,headers);
    let re = await httpc.post(config.openApi.url + url, JSON.stringify(rst), headers);
    let rs = await re.readBody();
    log.info({ url: url, requestBody: rst, header: headers, responseBody: JSON.parse(rs) })
    return rs;
}